﻿#include "SerialPortManager.h"

#include <qdebug.h>

SerialPortManager::SerialPortManager():QSerialPort()
{
  qRegisterMetaType<PrivateSignalClass>("PrivateSignalClass");
  qThread=new QThread();
  moveToThread(qThread);
  qThread->start();
  connect(this,&SerialPortManager::readyRead,this,&SerialPortManager::slot_readData,Qt::QueuedConnection);
  connect(this,&SerialPortManager::signal_sendData,this,&SerialPortManager::slot_sendData,Qt::QueuedConnection);
}
SerialPortManager::~SerialPortManager()
{
  close();
  qThread->quit();
  qThread->wait();
  delete qThread;
}

bool SerialPortManager::openSerialPort()
{
  return QSerialPort::open(QSerialPort::ReadWrite);
}

void SerialPortManager::sendData(QByteArray data)
{
  emit signal_sendData(data,PrivateSignal);
}

void SerialPortManager::init()
{
  setPortName("COM5");
  setBaudRate(460800);
  setDataBits(QSerialPort::Data8);
  setStopBits(QSerialPort::OneStop);
  setParity(QSerialPort::NoParity);
  setFlowControl(QSerialPort::NoFlowControl);
}

void SerialPortManager::slot_sendData(QByteArray data)
{
  if(isOpen())
    {
      write(data);
      flush();
    }
}

void SerialPortManager::slot_readData()
{
  emit signal_dataReceived(readAll(),PrivateSignal);
}

